#-*- coding: UTF-8 -*-
#@author terry
#主要用于模板拷贝
import sublime, sublime_plugin
import os
import os.path
import time
import sys
import re

from imp import reload
reload(sys)
ROOT_PTAH = 'XTool'
def write(view, str):
    view.run_command(
        'insert_snippet', {
            'contents': str
        }
    )
#写入模板，如果是新模板按照模板名创建一个文件，如果是旧模板则覆盖写原文件
class AddTemplateFileCommand(sublime_plugin.TextCommand):
	#加载模板文件
	def loadTemplate(self,path):
		print('path---',path)
		for x in os.listdir(path):
			tpath = os.path.join(path,x)
			if os.path.isdir(tpath):
				self.loadTemplate(tpath)
			else:
				if re.match(r".*\.lua$",x):
					template[x] = tpath
    
	def creat_tab(self, view, paths = [None],name="unitled"):
		win = view.window()
		tab = win.new_file()
		tab.set_name(name.lower())
		active = win.active_view()
		active.settings().set('default_dir', paths[0])
		return tab

	def run(self,edit,type=None, paths = [None]):
		#获取当前选中内容
		print ("ssssfaga")
		print ("type-->",type)
		if paths == [None]:
			paths[0] = self.view.window().extract_variables().get('folder','')
		if paths == [None] or type == None:
			return
		#加载模板库
		root = os.path.join(sublime.packages_path(),ROOT_PTAH,"template")
		globals()['template'] = {}
		self.loadTemplate(root)
		print("template",template)
		print ("ssss",paths)
		print (os.path.isdir(paths[0]))
		if type == "TemplateFunction.lua":
			self.currentUseTemplate = template.get(type)
			with open(self.currentUseTemplate, 'r',encoding='UTF-8') as f:
				self.readStr = f.read() 
				self.readStr = self.readStr.replace('\r', '')
				self.readStr = re.sub(r"(?<!\\)\${(?!\d)", '\${', self.readStr)	
			write(self.view,self.readStr)
			return


		#如果不存在该模板,则退出
		if not template.get(type):
			sublime.message_dialog("\u627e\u4e0d\u5230\u8be5\u6a21\u677f\u540d\u5b57")
			return
		self.currentUseTemplate = template.get(type)
		if not os.path.isdir(paths[0]):
			paths[0],_=os.path.split(paths[0]); 
			print("ssssss",paths[0])
		self.desPath = paths
		self.type = type ;


		

		def on_done(name):
			if name=='':
				sublime.message_dialog("\u547d\u540d\u4e0d\u80fd\u4e3a\u7a7a")
				return
			elif not re.match('^[a-zA-Z_$]*$',name):
				sublime.message_dialog("\u8f93\u5165\u7684\u6587\u4ef6\u540d\u4e0d\u89c4\u8303")
				return
			elif not name[0].isupper():
			    sublime.message_dialog("\u9700\u8981\u9996\u5b57\u6bcd\u5927\u5199")
			    return 
			#读取文件
			with open(self.currentUseTemplate, 'r',encoding='UTF-8') as f:
				self.readStr = f.read() 
				print('----',self.type.split('.')[0]);
				print('----',name.split('.')[0]);
				self.readStr = self.readStr.replace(self.type.split('.')[0],name.split('.')[0])
			#创建文件
			self.tab = self.creat_tab(self.view, self.desPath,name)
			self.tab.set_syntax_file("Packages/Lua/Lua.tmLanguage") #设置语法为lua
			self.tab.settings().set('default_extension', "lua")
			self.readStr = self.readStr.replace('\r', '') # replace \r\n -> \n
			self.readStr = re.sub(r"(?<!\\)\${(?!\d)", '\${', self.readStr)		
			self.tab.run_command('lucdocblock', {'head': True,'fileName':name,'fileContent':self.readStr})

		def on_change(name):
			return

		def on_cancel():
			return

		#输入模板名
		self.view.window().show_input_panel('Plese input the code template name',type.split('.')[0],on_done,on_change,on_cancel)

#将对应模板插入当前位置
class SearchTemplateFileCommand(sublime_plugin.TextCommand):

	def run(self,edit,paths = [None]):
		filenames = []
		print(paths)
		rootdir= os.path.join(sublime.packages_path(),ROOT_PTAH,"template")
		for p,d,files in os.walk(rootdir):
			filenames.extend(files)

		def on_done(selvalue):
			if selvalue==-1:
				return
			filename = filenames[selvalue]
			print('fileName',filename)
			self.view.run_command('add_template_file', {"type":filename,"paths":paths})
		#打开选择列表
		self.view.window().show_quick_panel(filenames,on_done)

